//
//  KeChengPingLunVC.m
//  ZhiBoYuan
//
//  Created by apple on 2018/4/17.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "KeChengPingLunVC.h"

#import "KeChengPingLun.h"

#import "CommentModel.h"
#import "ToolHeader.h"

static NSString *ident = @"KeChengPingLun";
#import "AppDelegate.h"

@interface KeChengPingLunVC ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;
//@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger pageIndex;


@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic,strong)UIButton *topButton;


@property (nonatomic,strong)UITextView *textview;


@property (nonatomic,strong)UIView *baciView;

@property (nonatomic, assign)BOOL canScroll;

@property (nonatomic, strong)UIButton *commiteBtn;

@property (nonatomic, strong)UILabel *textViewPlaceHo;

@property (nonatomic, assign)int page;

@property(nonatomic,assign)NSInteger xingNumber;

@end

@implementation KeChengPingLunVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _xingNumber = 5;
    
    _page = 1;
    
    _dataArray = [[NSMutableArray alloc] init];
    
    [self setupConfigureView];

    [self downloadCoursePingLunDatas];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:TABLETOP object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:TABLELEAVETOP object:nil];

    
}

- (void)acceptMsg:(NSNotification *)notification
{
    NSString *notificationName = notification.name;
    if ([notificationName isEqualToString:TABLETOP])
    {
        NSDictionary *userInfo = notification.userInfo;
        NSString *can = userInfo[NotificationCanScroll];
        if ([can isEqualToString:@"1"])
        {
            self.canScroll = YES;
            self.tableView.showsVerticalScrollIndicator = YES;
        }
        
    }
    else if ([notificationName isEqualToString:TABLELEAVETOP])
    {
        self.canScroll = NO;
        self.tableView.showsVerticalScrollIndicator = NO;
        self.tableView.contentOffset = CGPointZero;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!self.canScroll)
    {
        [scrollView setContentOffset:CGPointZero];
    }
    CGFloat offSetY = scrollView.contentOffset.y;
    
    if (offSetY < 0)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:TABLELEAVETOP object:nil userInfo:@{NotificationCanScroll: @"1"}];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)downloadCoursePingLunDatas{
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
                       @"course_id":self.course_id,
                       @"page_count":@"10",
                       @"page":[NSString stringWithFormat:@"%d",_page]
                       };
    [SGHttpTool POST:Host_Append(CourseComment) parameter:parameter sucess:^(id responseObject) {
        
        if (_page == 1) {
            [_dataArray removeAllObjects];
        }
        
        [_tableView.mj_footer endRefreshing];
        
        
        NNSLog(@"%@",responseObject);
        
        if ([responseObject[@"status"] intValue] == 200) {
            SGReceive *receive = [SGReceive receiveWithResponseObject:responseObject dataWord:@"comment_list"dataClass:[CommentModel class]];
            //        [self.dataArray addObjectsFromArray:receive.data];
            
            for (NSDictionary *dic in receive.data) {
                [_dataArray addObject:dic];
            }
            
            NNSLog(@"%@",_dataArray);
            
            [self.tableView reloadData];
        }else{
            [MBProgressHUD showTextOnly:self.view message:responseObject[@"msg"] delay:2.0];
            
        }
        
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
    
}


- (void)setupConfigureView{
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate        = self;
    self.tableView.dataSource      = self;
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    self.tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;//iOS8之后默认就是这个值，可以省略
    
    [self.tableView registerNib:[UINib nibWithNibName:ident bundle:nil] forCellReuseIdentifier:ident];
    
    [self.tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    
//    [self.view addSubview:self.topButton];
//
//    _topButton.sd_layout
//    .rightSpaceToView(self.view,20)
//    .bottomSpaceToView(self.view,2)
//    .heightIs(40).widthIs(40);
    
    
    //         上拉加载
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page = _page + 1;
        [self downloadCoursePingLunDatas];
    }];
    
    _tableView.sd_layout
    .topSpaceToView(self.view, 0)
    .rightSpaceToView(self.view,0)
    .bottomSpaceToView(self.view,0)
    .leftSpaceToView(self.view, 0);
    
}

-(UIView *)baciView{
    if (!_baciView) {
        _baciView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Screenheight)];
        
//        _baciView.backgroundColor = RGBA(0, 0, 0, 0.5);
        _baciView.backgroundColor = [UIColor whiteColor];
        _baciView.userInteractionEnabled=YES;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backAction)];

        [_baciView addGestureRecognizer:tap];
        
    }
    return _baciView;
}

-(void)backAction{
    [_textview resignFirstResponder];
    
}

-(void)hidensss{
    [self.baciView removeFromSuperview];
    
    [self.textview resignFirstResponder];
    
}

-(UIButton *)topButton{
    if (!_topButton) {
        _topButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_topButton setBackgroundImage:[UIImage imageNamed:@"组4"] forState:(UIControlStateNormal)];
        BTN_MSG_FUNC(_topButton, pingLunSender:);
        
    }
    return _topButton;
    
}

-(UIButton *)commiteBtn{
    if (!_commiteBtn) {
        _commiteBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _commiteBtn.frame = CGRectMake(20 * KscreenWidth, Screenheight - 150 * KscreenHeight, screenWidth - 40 * KscreenWidth, 50 * KscreenHeight);
        _commiteBtn.backgroundColor = ZhuTiColor;
        [_commiteBtn setTitle:@"提交" forState:0];
        BTN_MSG_FUNC(_commiteBtn, commiteSender:);
        
    }
    return _commiteBtn;
    
}
//提交

-(void)commiteSender:(UIButton *)sender{
    [self pinglunAction];
    
}
#pragma mark -----------------------  打开评论输入框页面  ------------------------

-(void)pingLunSender:(UIButton *)sender{
    NSLog(@"评论");
    
    
    
    AppDelegate *app =(AppDelegate *) [UIApplication sharedApplication].delegate;
    
    [app.window addSubview:self.baciView];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, NAVIGATION_BAR_HEIGHT)];
    view.backgroundColor = ZhuTiColor;
    [self.baciView addSubview:view];
    
    UIButton *Btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    Btn.frame = CGRectMake(10, STATUS_BAR_HEIGHT, NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT, NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT);
    [Btn setTitle:@"关闭" forState:0];
    
    BTN_MSG_FUNC(Btn, hidensss);
    [view addSubview:Btn];
    
    
    [self.baciView addSubview:self.commiteBtn];
    
    
    _textview =[[ UITextView alloc]initWithFrame:CGRectMake(20 * KscreenWidth, 220 * KscreenHeight, ScreenWidth-40 * KscreenWidth, 200 * KscreenHeight)];
    
    _textview.backgroundColor = [UIColor whiteColor];
    _textview.layer.borderColor = [hui2Color CGColor];
    _textview.layer.borderWidth = 1;
    _textview.font = [UIFont systemFontOfSize:16 * KscreenWidth];
    _textview.returnKeyType = UIReturnKeySend;
    _textview.delegate = self;
    
    _textview.inputAccessoryView = [[UIView alloc] init];
    
    
    
    [self.baciView addSubview:self.textview];
    
    _textViewPlaceHo = [[UILabel alloc]initWithFrame:CGRectMake(5 * KscreenWidth,7 * KscreenHeight, screenWidth - 10 * KscreenWidth, 20 * KscreenHeight)];
    _textViewPlaceHo.text = @"评价不能为空，字数上限200字";
    _textViewPlaceHo.textColor = hui2Color;
    _textViewPlaceHo.font = [UIFont systemFontOfSize:18 * KscreenWidth];
    [self.textview addSubview:_textViewPlaceHo];
    
    
    _xingNumber = 5;
    
    [self addXing];

    self.textview.text = @"";
    
}

-(void)addXing {
    
    NSMutableArray *nameArr =@[].mutableCopy;
    
    for (int i = 0; i< 5; i++) {
        if ( i >= _xingNumber)
        {
            [nameArr addObject:@"五角星-1副本5"]; // 黄星星
        }
        else
        {
            [nameArr addObject:@"五角星-1"];  // 灰色星星
        }
    }
    
    NSMutableArray* buttons = [NSMutableArray arrayWithCapacity:5];
    CGRect btnRect = CGRectMake(90 * KscreenWidth, 120 * KscreenHeight, 40 * KscreenWidth, 40 * KscreenHeight);
    
    int i = 0;
    
    for (NSString* optionTitle in nameArr)
    {
        i++;
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:btnRect];
        btnRect.origin.x += 50 * KscreenWidth;
        imageView.image = [UIImage imageNamed:optionTitle];
       imageView.userInteractionEnabled =YES;
        
         __weak __typeof(&*self)weakSelf = self;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
            
            UIView *tagVie = ((UITapGestureRecognizer *)sender).view;
            
            NSLog(@"%zd",tagVie.tag);
            weakSelf.xingNumber = tagVie.tag;
            
            [weakSelf addXing];

            for (UIView *view in buttons) {
                [view removeFromSuperview];
            }
            
            
        }];
        [imageView addGestureRecognizer:tap];
        
        
        imageView.tag = i;
 
        [_baciView addSubview:imageView];
        [buttons addObject:imageView];
    }

    

}



-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_textview resignFirstResponder];
    
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];//按回车取消第一相应者
    }
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.textViewPlaceHo.hidden = YES;
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{//将要停止编辑(不是第一响应者时)
    if (textView.text.length == 0) {
        self.textViewPlaceHo.hidden = NO;
    }
    return YES;
}

#pragma mark ----------------------- 提交评论内容 ------------------------

-(void)pinglunAction{
    
    
    [MBProgressHUD showLoadingImageToView:_baciView];
    
    if (_textview.text.length > 200) {
        [MBProgressHUD showTextOnly:_baciView message:@"请输入200字以内的评论" delay:2.0];
        return;
    }
    
    if (_textview.text.length == 0) {
        [MBProgressHUD showTextOnly:_baciView message:@"评论不能为空" delay:2.0];
        return;
    }
    
    
//   self.xingNumber
    
    [NSString stringWithFormat:@"%zd",self.xingNumber];
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{@"course_id":self.course_id,
                       @"content":_textview.text,
                       @"star_num":[NSString stringWithFormat:@"%zd",self.xingNumber]
                       
                       };
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Comment&a=courseComment",HTTPP] parameter:parameter sucess:^(id responseObject) {
        
        [MBProgressHUD hideHUDForView:_baciView animated:YES];
        
        NSLog(@"%@",responseObject);
        NSDictionary *dic = responseObject;
        
        if ([dic[@"status"] intValue] == 200) {
            
            [self.baciView removeFromSuperview];

            
            [MBProgressHUD showTextOnly:_baciView message:dic[@"msg"] delay:2.0f];
            
            _page= 1;
            _dataArray = [NSMutableArray array];

            
            [self downloadCoursePingLunDatas];
            
            
        }else{
            [MBProgressHUD showTextOnly:_baciView message:dic[@"msg"] delay:2.0f];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
    
}

#pragma mark -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    KeChengPingLun *cell = [tableView dequeueReusableCellWithIdentifier:ident forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    //    cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
    //    zjsDataBaseLesson *data = self.lessonArray[indexPath.row];
    //    [cell loadData:data];
    cell.model = self.dataArray[indexPath.row];
    
    return cell;
    
    
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return SNRealValue(50);
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //    AdetailViewController *vc= [[AdetailViewController alloc]initWithNibName:@"AdetailViewController" bundle:nil];
    //
    //    vc.hidesBottomBarWhenPushed =YES;
    //
    //    [self.navigationController pushViewController:vc animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
